package fanketly.core.lib.base.utils

import android.content.Context
import com.blankj.utilcode.util.ToastUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions

/**
 *Create by Fanketly on 2022/9/13
 *Gitee:https://gitee.com/fanketly
 *desc:
 */
object PermissionsUtils {

    /**
     * 申请权限
     * 仅需要处理成功时传入onGranted，但不能传入callback
     * 自定义处理时传入callback
     * 当项目的 targetSdkVersion >= 30 时，则不能申请 READ_EXTERNAL_STORAGE 和 WRITE_EXTERNAL_STORAGE 权限，
     * 而是应该申请 MANAGE_EXTERNAL_STORAGE 权限
     */
    fun openPermissions(
        context: Context,
        vararg permissions: String,
        onGranted: ((permissions: List<String>, all: Boolean) -> Unit)? = null,
        callback: OnPermissionCallback? = null
    ) {
        XXPermissions.with(context) // 申请单个权限
            //                .permission(Permission.WRITE_EXTERNAL_STORAGE)
            //                .permission(Permission.READ_EXTERNAL_STORAGE)
            .permission(permissions)
//            .permission(Permission.ACCESS_FINE_LOCATION)
//            .permission(Permission.ACCESS_COARSE_LOCATION)
//            .permission(Permission.REQUEST_INSTALL_PACKAGES)
//            .permission(Permission.CAMERA)
//                .permission("android.permission.FOREGROUND_SERVICE")
            // 申请多个权限
            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            //.unchecked()
            .request(callback ?: object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    onGranted?.invoke(permissions, all)
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {
                    if (never) {
                        ToastUtils.showShort("拒绝会导致功能无法正常使用")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(context, permissions)
                    } else {
                        ToastUtils.showShort("拒绝会导致功能无法正常使用")
                    }
                }
            })
    }
}